package com.snap.vseries.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.snap.vseries.AppConfig;
import com.snap.vseries.R;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.bean.SerialPortDevice;
import com.snap.vseries.bean.SettingInfo;
import com.snap.vseries.dialog.NormalCountDialog;
import com.snap.vseries.framework.MoleExecutor;
import com.snap.vseries.framework.MoleTask;
import com.snap.vseries.manager.ConfigManager;
import com.snap.vseries.manager.FileManager;
import com.snap.vseries.threadmanager.ThreadListener;
import com.snap.vseries.threadmanager.ThreadManger;
import com.snap.vseries.ui.widget.DialogView;
import com.snap.vseries.update.UpdateCmd;
import com.snap.vseries.update.UpdateManager;
import com.snap.vseries.update.UpdateSerialPortHelper;
import com.snap.vseries.utils.RootShellCmd;
import com.snap.vseries.utils.ToastUtils;
import com.snap.vseries.utils.TopTitleUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.MessageFormat;

import butterknife.BindView;
import butterknife.OnClick;

import static com.snap.vseries.AppConfig.SERIAL_BAUD_RATE;
import static com.snap.vseries.AppConfig.SERIAL_PORT;

/**l
 * //彩蛋页面
 * Created by Eason on 2019-07-25 .
 */
public class EggActivity extends BaseActivity {


    @BindView(R.id.show_temp_value_cb)
    CheckBox showTempValueCb;

    @BindView(R.id.permission_cb)
    CheckBox permissionCb;
    @BindView(R.id.analysis_debug_cb)
    CheckBox analysisDebugCb;

    @BindView(R.id.increase_velocity_tv)
    TextView increaseVelocityTv;
    @BindView(R.id.decrease_velocity_tv)
    TextView decreaseVelocityTv;
    @BindView(R.id.increase_fit_tv1)
    TextView increaseFitTv1;
    @BindView(R.id.increase_fit_tv2)
    TextView increaseFitTv2;
    @BindView(R.id.increase_fit_tv3)
    TextView increaseFitTv3;
    @BindView(R.id.increase_fit_tv4)
    TextView increaseFitTv4;
    @BindView(R.id.decrease_fit_tv1)
    TextView decreaseFitTv1;
    @BindView(R.id.decrease_fit_tv2)
    TextView decreaseFitTv2;
    @BindView(R.id.decrease_fit_tv3)
    TextView decreaseFitTv3;
    @BindView(R.id.decrease_fit_tv4)
    TextView decreaseFitTv4;

    @BindView(R.id.debug_origin_light_cb)
    CheckBox debugOriginLightCb;
    @BindView(R.id.show_fit_process_cb)
    CheckBox showFitProcessCb;
    @BindView(R.id.light_base_tv)
    TextView lightBaseTv;
    @BindView(R.id.fit_offset_tv)
    TextView fitOffsetTv;

    @BindView(R.id.memory_size_tv)
    TextView memorySizeTv;
    @BindView(R.id.hard1_update_tv)
    TextView hard1UpdateTv;
    @BindView(R.id.get_version_tv)
    TextView getVersionTv;
    @BindView(R.id.update_force_cb)
    CheckBox updateCb;
    @BindView(R.id.cit_test_tv)
    TextView citTestTv;

    @Override
    protected int layoutResId() {
        return R.layout.activity_egg;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TopTitleUtils(this).setTitle("动态配置");
        SettingInfo settingInfo = ConfigManager.getInstance().getSettingInfo();
        permissionCb.setChecked(AppConfig.Dynamic.developer_permission);
        //=========================测试数据===========================
        permissionCb.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.developer_permission = isChecked);
        //温度相关设置项
        //温度图表显示具体温度数值
        showTempValueCb.setChecked(AppConfig.Dynamic.show_temp_value);
        showTempValueCb.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.show_temp_value = isChecked);

        //升降温速率配置
        increaseVelocityTv.setText(String.valueOf(settingInfo.getIncreaseVelocity()));
        increaseVelocityTv.setOnClickListener(v -> {
            new DialogView(EggActivity.this)
                    .setTitle("升温速率配置")
                    .setHint("升温速率")
                    .setContentType(false)
                    .setEditContent(increaseVelocityTv.getText().toString())
                    .setOnClickListener(content -> {
                        float value = Float.valueOf(content);
                        if (value < 0.5f || value > 10f) {
                            ToastUtils.get().showText("错误的配置！");
                            return;
                        }
                        value = (float) (Math.round(value * 100)) / 100;
                        increaseVelocityTv.setText(String.valueOf(value));
                        settingInfo.setIncreaseVelocity(value);
                        ConfigManager.getInstance().update();
                    }).show();
        });
        //调试分析算法开关
        analysisDebugCb.setChecked(AppConfig.Dynamic.analysis_debug_mode);
        analysisDebugCb.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.analysis_debug_mode = isChecked);
        decreaseVelocityTv.setText(String.valueOf(settingInfo.getDecreaseVelocity()));
        decreaseVelocityTv.setOnClickListener(v -> {
            new DialogView(EggActivity.this)
                    .setTitle("降温速率配置")
                    .setHint("降温速率")
                    .setContentType(false)
                    .setEditContent(decreaseVelocityTv.getText().toString())
                    .setOnClickListener(content -> {
                        float value = Float.valueOf(content);
                        if (value < 0.5f || value > 10f) {
                            ToastUtils.get().showText("错误的配置！");
                            return;
                        }
                        value = (float) (Math.round(value * 100)) / 100;
                        decreaseVelocityTv.setText(String.valueOf(value));
                        settingInfo.setDecreaseVelocity(value);
                        ConfigManager.getInstance().update();
                    }).show();
        });

        //温度曲线拟合
        increaseFitTv1.setText(String.valueOf(settingInfo.getIncreaseThreshold()));
        increaseFitTv2.setText(String.valueOf(settingInfo.getIncreasePreValue()));
        increaseFitTv3.setText(String.valueOf(settingInfo.getIncreaseT1()));
        increaseFitTv4.setText(String.valueOf(settingInfo.getIncreaseT2()));
        decreaseFitTv1.setText(String.valueOf(settingInfo.getDecreaseThreshold()));
        decreaseFitTv2.setText(String.valueOf(settingInfo.getDecreasePreValue()));
        decreaseFitTv3.setText(String.valueOf(settingInfo.getDecreaseT1()));
        decreaseFitTv4.setText(String.valueOf(settingInfo.getDecreaseT2()));
        increaseFitTv1.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getIncreaseThreshold(), 120, "起点温度", "°C", count -> {
                    increaseFitTv1.setText(String.valueOf(count));
                    settingInfo.setIncreaseThreshold(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        increaseFitTv2.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getIncreasePreValue(), 5, "提前温度", "°C", count -> {
                    increaseFitTv2.setText(String.valueOf(count));
                    settingInfo.setIncreasePreValue(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        increaseFitTv3.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getIncreaseT1(), 20, "T1", "s", count -> {
                    increaseFitTv3.setText(String.valueOf(count));
                    settingInfo.setIncreaseT1(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        increaseFitTv4.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getIncreaseT2(), 10, "T2", "s", count -> {
                    increaseFitTv4.setText(String.valueOf(count));
                    settingInfo.setIncreaseT2(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));

        decreaseFitTv1.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getDecreaseThreshold(), 120, "起点温度", "°C", count -> {
                    decreaseFitTv1.setText(String.valueOf(count));
                    settingInfo.setDecreaseThreshold(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        decreaseFitTv2.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getDecreasePreValue(), 5, "提前温度", "°C", count -> {
                    decreaseFitTv2.setText(String.valueOf(count));
                    settingInfo.setDecreasePreValue(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        decreaseFitTv3.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getDecreaseT1(), 20, "T1", "s", count -> {
                    decreaseFitTv3.setText(String.valueOf(count));
                    settingInfo.setDecreaseT1(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));
        decreaseFitTv4.setOnClickListener(v ->
                new NormalCountDialog().setParam(settingInfo.getDecreaseT2(), 10, "T2", "s", count -> {
                    decreaseFitTv4.setText(String.valueOf(count));
                    settingInfo.setDecreaseT2(count);
                    ConfigManager.getInstance().update();
                }).show(getSupportFragmentManager(), ""));

        //荧光相关设置项
        //展示原始荧光的选项
        debugOriginLightCb.setChecked(AppConfig.Dynamic.exp_running_debug_origin_light);
        debugOriginLightCb.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.exp_running_debug_origin_light = isChecked);

        //实验详情显示拟合过程
        showFitProcessCb.setChecked(AppConfig.Dynamic.exp_detail_show_fit_step);
        showFitProcessCb.setOnCheckedChangeListener((buttonView, isChecked) -> AppConfig.Dynamic.exp_detail_show_fit_step = isChecked);

        //荧光基数配置
        lightBaseTv.setText(String.valueOf(settingInfo.getLightBase()));
        lightBaseTv.setOnClickListener(v -> new DialogView(EggActivity.this)
                .setTitle("荧光基数配置")
                .setHint("荧光基数")
                .setEditContent(lightBaseTv.getText().toString())
                .setOnClickListener(content -> {
                    int value = Integer.valueOf(content);
                    lightBaseTv.setText(String.valueOf(value));
                    settingInfo.setLightBase(value);
                    ConfigManager.getInstance().update();
                }).show());

        //孔间拟合偏移
        fitOffsetTv.setText(String.valueOf(settingInfo.getFitOffset()));
        fitOffsetTv.setOnClickListener(v -> {
            new DialogView(EggActivity.this)
                    .setTitle("孔间拟合偏移")
                    .setHint("偏移量")
                    .setContentType(true)
                    .setEditContent(fitOffsetTv.getText().toString())
                    .setOnClickListener(content -> {
                        float value = Float.valueOf(content);
                        if (value < -0.1f || value > 0.1f) {
                            ToastUtils.get().showText("错误的配置！");
                            return;
                        }
                        value = (float) (Math.round(value * 1000)) / 1000;
                        fitOffsetTv.setText(String.valueOf(value));
                        settingInfo.setFitOffset(value);
                        ConfigManager.getInstance().update();
                    }).show();
        });

        //右半部分
        memorySizeTv.setText("内存容量:" + getTotalMemory());
        hard1UpdateTv.setOnClickListener(v -> {
            UpdateManager.getInstance().doUpdate(this, updateCb.isChecked());
        });

        getVersionTv.setOnClickListener(v -> {
            MoleExecutor.getInstance().execute(new MoleTask<String>() {
                @Override
                public String runInBackground() throws InterruptedException {
                    String res = null;
                    UpdateSerialPortHelper serialPortHelper = new UpdateSerialPortHelper(new SerialPortDevice(SERIAL_PORT, SERIAL_BAUD_RATE));
                    try {
                        serialPortHelper.open();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Bundle b = serialPortHelper.execute(UpdateCmd.getHardInfo(1));
                    if (b.getBoolean("suc")) {
                        byte[] data = b.getByteArray("data");
                        if (data != null) {
                            int v1 = data[11];
                            int v2 = data[12];
                            int v3 = data[13];
                            res = v1 + "." + v2 + "." + v3;
                        }
                    }
                    serialPortHelper.close();
                    return res;
                }

                @Override
                public void onCompleted(String result) {
                    ToastUtils.get().showText(MessageFormat.format("硬件版本：{0}", result));
                }
            });
        });
        citTestTv.setOnClickListener(v -> startActivity(new Intent(EggActivity.this, CitTestActivity.class)));
    }

    public void escape(View v) {
        RootShellCmd.getInstance().showNavigation();
//        EggActivity.this.sendBroadcast(new Intent("com.tchip.changeBarHideStatus"));
        RootShellCmd.getInstance().escape();
    }

    public void hideNavigation(View v) {
        RootShellCmd.getInstance().hideNavigation();
//        EggActivity.this.sendBroadcast(new Intent("com.tchip.changeBarHideStatus"));
    }

    private String getTotalMemory() {
        // 系统内存信息文件
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            // 读取meminfo第一行，系统总内存大小
            str2 = localBufferedReader.readLine();

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            // 获得系统总内存，单位是KB，乘以1024转换为Byte
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;
            localBufferedReader.close();

        } catch (IOException e) {
        }
        // Byte转换为KB或者MB，内存大小规格化
        return Formatter.formatFileSize(getBaseContext(), initial_memory);
    }

    /**
     * TODO: 2020/4/10 日志文件多久清除一次
     *
     * @param view
     */
    public void deleteDirectory(View view) {
        new DialogView(EggActivity.this)
                .setTitle("清除所有实验数据")
                .setTextContent("确认清除所有实验数据？")
                .setOnClickListener(new DialogView.OnSureListener() {
                    @Override
                    public void onSureClick(String content) {
                        ThreadManger.get().add(new ThreadListener() {
                            @Override
                            public void doAction() throws Exception {
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + AppConfig.ROOT_DIRECTORY;
                                boolean result = FileManager.getInstance().deleteDirectory(path);
                                if (result) {
                                    ToastUtils.get().showText("清除所有实验数据成功");
                                }
                            }
                        });
                    }
                }).show();
    }

    @OnClick({R.id.pid_setting_tv, R.id.temp_drift_setting_tv})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pid_setting_tv:
                Intent pidIntent = new Intent(this, PidSettingActivity.class);
                startActivity(pidIntent);
                break;
            case R.id.temp_drift_setting_tv:
                //温漂设置
                Intent tempIntent = new Intent(this, TempDriftSettingActivity.class);
                startActivity(tempIntent);
                break;
            default:
        }
    }
}